import React from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Button, Input, Select, message, Row, Col, Tabs, AutoComplete, Spin } from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { urlParse } from '@/utils/utils';
import styles from '@/utils/utils.less';
import Area from '../../components/Area';
import Invoice from './update/invoice';
import MailingAddress from './update/mailingaddress';
import Bank from './update/bank';
import Contact from './update/contact';

const FormItem = Form.Item;
const { TabPane } = Tabs;
const { Search } = Input;
const { Option } = Select;

@connect(({ loading }) => ({
  loading: loading.models.suppliermaintenance,
}))
class BasicForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      dictList: [
        'SUPP_TYPE',
        'SUPPER_DETAIL_TAB',
        'MINI_INV_TYPE',
        'TAXPAYER_TYPE',
        'BANK_ID',
        'GENDER',
        'HAS_CHILD',
      ],
      suppId: '',
      isHasSuppType: false,
      tabList: [],
      activeKey: '1',
      subActiveKey: '1',
      taxerTypeList: [],
      genderList: [],
      hasChildList: [],
      suppTypeList: [],
      custList: [],
      custMessage: {},
    };
  }

  componentDidMount() {
    const { dispatch, location, form } = this.props;
    const { suppId, activeKey, subActiveKey, dictList } = this.state;
    const suppId1 = urlParse(location.search).suppId ? urlParse(location.search).suppId : suppId;
    const activeKey1 = urlParse(location.search).activeKey
      ? urlParse(location.search).activeKey
      : activeKey;
    const subActiveKey1 = urlParse(location.search).subActiveKey
      ? urlParse(location.search).subActiveKey
      : subActiveKey;
    this.setState({
      suppId: suppId1,
      activeKey: activeKey1,
      subActiveKey: subActiveKey1,
      isHasSuppType: String(activeKey1) === '1',
    });
    // 获取页面所需字典
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: dictList,
    })
      .then(data => {
        const suppTypeList = [];
        data.SUPP_TYPE.forEach(item => {
          if (item.itemCode !== '1' && item.itemCode !== '4') {
            suppTypeList.push(item);
          }
        });
        const sortNumber = (a, b) => a.itemCode - b.itemCode;
        data.SUPPER_DETAIL_TAB.sort(sortNumber);
        this.setState({
          bankList: data.BANK_ID,
          hasChildList: data.HAS_CHILD,
          taxerTypeList: data.MINI_INV_TYPE,
          tabList: data.SUPPER_DETAIL_TAB,
          suppTypeList,
        });
      })
      .then(() => {
        dispatch({
          type: 'suppliermaintenance/fetchInfo',
          payload: { suppId: suppId1 },
          callback: res => {
            this.setState({ loading: false, suppId: suppId1, activeKey: activeKey1 });
            if (res.success && res.data) {
              const getFieldsList = form.getFieldsValue();
              Object.keys(getFieldsList).forEach(key => {
                if (res.data[key]) {
                  if (key === 'areaId') {
                    form.setFieldsValue({
                      [key]: { key: res.data.areaId, label: res.data.areaName },
                    });
                  } else if (key === 'type') {
                    form.setFieldsValue({
                      [key]: { key: `${res.data[key] && res.data[key]}` },
                    });
                  } else {
                    form.setFieldsValue({ [key]: res.data[key] });
                  }
                }
              });
              // 供应商名称初始值
              this.state.custMessage = res.data;
            } else {
              message.warning(`${res.message || '服务端错误！'}`);
            }
          },
        });
      });
  }

  // 地区
  getData = (value, id) => {
    const tempAreaId = value.key;
    const { form } = this.props;
    if (id) {
      form.setFieldsValue({ [id]: { key: tempAreaId } });
      this.setState({ [id]: tempAreaId });
    }
  };

  // 选择某一供应商
  selectCust = (custId, options) => {
    console.log(custId, options,options.props.options,'options.props.options');
    const { custList, custMessage } = this.state;
    const { form } = this.props;
    // if (options.props.options) {
      // 选中的
      let custInfo = null;
      custList.forEach(item => {
        if (custId === item.mdSuppId) {
          custInfo = item;
        }
      });
      this.setState({
        custMessage: custInfo,
      });
      const getFieldsList = form.getFieldsValue();
      console.log(getFieldsList,'getFieldsList');
      Object.keys(getFieldsList).forEach(key => {
        if (custInfo[key]) {
          if (key === 'corpNature' || key === 'industryCode') {
            form.setFieldsValue({ [key]: { key: `${custInfo[key]}`, mdCustId: null } });
            form.setFieldsValue({ no: null });
          } else if (key === 'areaId') {
            form.setFieldsValue({
              [key]: { key: custInfo.areaId, label: custInfo.areaName },
            });
          } else {
            form.setFieldsValue({ [key]: custInfo[key], mdCustId: null });
            form.setFieldsValue({ no: null });
          }
        }
      });
    // } else {
    //   custMessage.name =custId;
    //   this.setState({
    //     custMessage,
    //   });
    // }
  };

  // 切换页签
  changeTabPane = activeKey1 => {
    this.setState({ subActiveKey: activeKey1 });
    const { suppId, activeKey } = this.state;
    router.push(
      `/supplymanage/protection/update?suppId=${suppId}&activeKey=${activeKey}&subActiveKey=${activeKey1}`
    );
  };

  // 搜索供应商
  searchCust = value => {
    console.log(value,"value")
    const { dispatch, form } = this.props;
    this.setState({ loading: true });
    dispatch({
      type: 'suppliermaintenance/fetchNameList',
      payload: { name: value },
      callback: res => {
        this.setState({ loading: false });
        if (res.success && res.data) {
          console.log( res.data,' res.data')
          this.setState({
            custList: res.data,
          });
          const getFieldsList = form.getFieldsValue();
          Object.keys(getFieldsList).forEach(key => {
            if(!res.data.length){
              form.setFieldsValue({ name: value, mdSuppId: null });
              form.setFieldsValue({ no: null });
            }
            if (key === 'corpNature' || key === 'industryCode') {
              form.setFieldsValue({ no: null });
              form.setFieldsValue({
                [key]: { key: `${res.data[key]}`, mdSuppId: null },
              });
              form.setFieldsValue({ no: null });
            } else if (key === 'areaId') {
              if(!res.data.length&&!res.data.areaId){
                form.setFieldsValue({
                  [key]: undefined,
                });
              }else{  
              // form.setFieldsValue({
              //   [key]: { key: res.data.areaId, label: res.data.areaName },
              // });
            }
            } else {
              form.setFieldsValue({ [key]: res.data[key], mdSuppId: null });
              form.setFieldsValue({ no: null });
            }
          });
        } else {
          this.setState({ custList: [] });
        }
      },
    });
  };

  searchCusttwo = value => {
    const { dispatch, form } = this.props;
    this.setState({ loading: true });
    dispatch({
      type: 'suppliermaintenance/fetchSuppList',
      payload: { uniCreditCode: value },
      callback: res => {
        this.setState({ loading: false });
        // if (!res.data.areaId || !res.data.mdSuppId) {
        //   form.resetFields(['name', 'areaId']);
        // }
        if (res.success) {
          const getFieldsList = form.getFieldsValue();
          Object.keys(getFieldsList).forEach(key => {
            if (res.data[key]) {
              if (key === 'corpNature' || key === 'industryCode') {
                form.setFieldsValue({
                  [key]: { key: `${res.data[key]}`, mdCustId: null },
                });
                form.setFieldsValue({ no: null });
              } else if (key === 'areaId') {
                form.setFieldsValue({
                  [key]: { key: res.data.areaId, label: res.data.areaName },
                });
              } else {
                form.setFieldsValue({ [key]: res.data[key], mdCustId: null });
                form.setFieldsValue({ no: null });
              }
            }
          });
        } else {
          this.setState({ loading: false });
        }
      },
    });
  };

  slelce = e => {
    const { custList,form,custMessage } = this.state;
    let names = '';
    custMessage.name= e
    custList.forEach(item => {
      if (e === item.mdSuppId) {
        console.log(item,'custMessage'); 
        
        names = 1;
      }
    });
  };

  slelcetwo = () => {
    // var lllo = '';
  };

  selectCusttwo = () => {
    // let custInfo = null;
  };

  // 提交
  sumSubmit = e => {
    const { dispatch, form } = this.props;
    e.preventDefault();
    const { suppId, activeKey, custMessage } = this.state;
    const data = {};
    let submitData = {};
    form.validateFieldsAndScroll((error, values) => {
      if (!error) {
        Object.keys(values).forEach(key => {
          if (values[key] && values[key].key) {
            data[key] = values[key].key;
          } else if (key === 'areaId') {
            const arr = values[key][1];
            data[key] = arr;
          } else {
            data[key] = values[key] ? values[key] : '';
          }
          data.name = custMessage.name;
        });

        submitData = { ...data, suppId };
        this.setState({ loading: true });
        if (String(activeKey) === '1') {
          dispatch({
            type: 'suppliermaintenance/updatePla',
            payload: submitData,
            callback: res => {
              if (res.success) {
                this.setState({ loading: false });
                message.success('修改成功！', 2, () => {
                  router.push(`/supplymanage/protection/index?activeKey=${activeKey}`);
                });
              } else {
                this.setState({ loading: false });
                message.warning(`${res.message || '修改失败！'}`);
              }
            },
          });
        } else {
          dispatch({
            type: 'suppliermaintenance/update',
            payload: submitData,
            callback: res => {
              if (res.success) {
                this.setState({ loading: false });
                message.success('修改成功！', 2, () => {
                  router.push(`/supplymanage/protection/index?activeKey=${activeKey}`);
                });
              } else {
                this.setState({ loading: false });
                message.warning(`${res.message || '修改失败！'}`);
              }
            },
          });
        }
      }
    });
  };

  render() {
    const {
      loading,
      suppId,
      activeKey,
      subActiveKey,
      tabList,
      isHasSuppType,
      suppTypeList,
      taxerTypeList,
      bankList,
      genderList,
      hasChildList,
      custList,
    } = this.state;
    const { form } = this.props;
    const { getFieldDecorator } = form;
    const xl = { span: 8 };
    const lg = { span: 8 };
    const md = { span: 8 };
    const sm = 24;
    const colProps = { xl, lg, md, sm };
    // 供应商类型
    const suppTypeOL = suppTypeList.map(options => (
      <Option key={options.itemCode}>{options.itemName}</Option>
    ));
    const options =
      custList.length > 0 &&
      custList.map(opt => (
        <Option key={opt.mdSuppId} value={opt.mdSuppId}>
          {opt.name}
        </Option>
      ));
    // 下拉选项
    const BasicInfo = (
      <div>
        <Form layout="vertical">
          <Row gutter={64}>
            <Col {...colProps}>
              <FormItem label="供应商名称">
                {getFieldDecorator('name', {
                  rules: [{ required: true, message: '请输入' }],
                })(
                  <AutoComplete
                    dataSource={options}
                    onSelect={this.selectCust}
                    onChange={this.slelce}
                    disabled={!isHasSuppType}
                  >
                    <Search
                      placeholder="请输入关键字检索"
                      maxLength={100}
                      onSearch={value => this.searchCust(value)}
                    />
                  </AutoComplete>
                )}
              </FormItem>
            </Col>
            {isHasSuppType ? (
              <Col {...colProps}>
                <FormItem label="供应商类型">
                  {getFieldDecorator('type', {
                    rules: [{ required: true, message: '请选择' }],
                  })(
                    <Select
                      placeholder="请选择"
                      style={{ width: '100%' }}
                      labelInValue
                      optionFilterProp="children"
                    >
                      {suppTypeOL}
                    </Select>
                  )}
                </FormItem>
              </Col>
            ) : null}
            <Col {...colProps}>
              <FormItem label="地区">
                {getFieldDecorator('areaId', {
                  rules: [{ required: true, message: '请选择' }],
                })(
                  <Area
                    disabled={!isHasSuppType}
                    onChange={value => this.getData(value, 'areaId')}
                    labelInValue
                  />
                )}
              </FormItem>
            </Col>
            {isHasSuppType ? <div style={{ clear: 'both' }} /> : null}

            <Col {...colProps}>
              <FormItem label="统一社会信用代码">
                {getFieldDecorator('uniCreditCode', {
                  rules: [
                    {
                      required: true,
                      message: '长度为18位的数字与字母组合',
                      pattern: /^[A-Za-z0-9]{18}$/,
                    },
                  ],
                })(
                  Number(activeKey) === 1 ? (
                    <AutoComplete
                      // dataSource={optionstwo}
                      onSelect={this.selectCusttwo}
                      onChange={this.slelcetwo}
                      disabled={!isHasSuppType}
                    >
                      <Search
                        placeholder="请输入关键字检索"
                        maxLength={100}
                        onSearch={value => this.searchCusttwo(value)}
                      />
                    </AutoComplete>
                  ) : (
                    <Input placeholder="请输入" disabled={Number(activeKey) !== 1} />
                  )

                  //
                )}
              </FormItem>
            </Col>
            {Number(activeKey) === 1 ? null : <div style={{ clear: 'both' }} />}
            <Col {...colProps}>
              <FormItem label="办公地址">
                {getFieldDecorator('officeAddr', {})(
                  <Input placeholder="请输入" maxLength={100} />
                )}
              </FormItem>
            </Col>
            <Col {...colProps}>
              <FormItem label="工作邮箱">
                {getFieldDecorator('email', {
                  rules: [{ type: 'email', message: '应为邮箱格式' }],
                })(<Input placeholder="请输入" maxLength={50} />)}
              </FormItem>
            </Col>
            {isHasSuppType ? <div style={{ clear: 'both' }} /> : null}
            <Col {...colProps}>
              <FormItem label="联系电话">
                {getFieldDecorator('tel', {
                  rules: [
                    {
                      required: false,
                      message: '固话或手机',
                      pattern: /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/,
                    },
                  ],
                })(<Input placeholder="请输入" maxLength={12} />)}
              </FormItem>
            </Col>
            <Col {...colProps}>
              <FormItem label="备注">
                {getFieldDecorator('remark', {})(<Input placeholder="请输入" maxLength={200} />)}
              </FormItem>
            </Col>
          </Row>
        </Form>
        <div
          style={{
            marginTop: 100,
            paddingTop: 24,
            marginBottom: 16,
            textAlign: 'right',
            boxShadow: '0 -1px 2px rgba(0, 0, 0, 0.03)',
            borderTop: '1px solid #e8e8e8',
          }}
        >
          <Button
            onClick={() => router.push(`/supplymanage/protection/index?activeKey=${activeKey}`)}
            style={{ marginRight: 10 }}
          >
            取消
          </Button>
          <Button type="primary" onClick={this.sumSubmit}>
            提交
          </Button>
        </div>
      </div>
    );
    // 获取页签组件
    const getTabPane = activeKey1 => {
      switch (activeKey1) {
        case '1':
          return BasicInfo;
        case '2':
          return <Invoice suppId={suppId} taxerTypeList={taxerTypeList} />;
        case '3':
          return <MailingAddress suppId={suppId} />;
        case '4':
          return <Bank suppId={suppId} bankList={bankList} />;
        case '5':
          return <Contact suppId={suppId} genderList={genderList} hasChildList={hasChildList} />;
        default:
          return <div />;
      }
    };
    return (
      <PageHeaderWrapper>
        <Card className={styles.tabCard}>
          <Spin tip="Loading..." spinning={loading}>
            <Tabs activeKey={subActiveKey} onChange={this.changeTabPane}>
              {tabList.map(pane => (
                <TabPane tab={pane.itemName} key={pane.itemCode}>
                  {getTabPane(pane.itemCode)}
                </TabPane>
              ))}
            </Tabs>
          </Spin>
        </Card>
      </PageHeaderWrapper>
    );
  }
}
const BasicFormList = Form.create()(BasicForm);
export default BasicFormList;
